import subprocess
import os
from videofilesystem import extract_videos_direct,extract_videos_anyway

def get_video_duration(input_path):
    """获取视频时长（秒）"""
    cmd = [
        'ffprobe', '-v', 'error',
        '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1',
        input_path
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if result.returncode != 0:
        raise Exception(f"获取视频时长失败: {result.stderr}")
    return float(result.stdout.strip())

def split_video(input_path, output_prefix, num_segments):
    """
    使用关键帧对齐的智能分割方法（带存在性检查）
    :param input_path: 输入视频路径
    :param output_prefix: 输出文件前缀（如输出 output_1.mp4）
    :param num_segments: 分割份数
    """
    # 检查首片段文件是否已存在
    first_segment = f"{output_prefix}_1.mp4"
    if os.path.exists(first_segment):
        print(f"检测到已存在分割文件 {first_segment}，跳过处理")
        return

    # 执行视频分割
    total_duration = get_video_duration(input_path)
    segment_duration = total_duration / num_segments

    # 生成关键帧对齐的分割时间点
    segment_times = [segment_duration * i for i in range(1, num_segments)]
    times_str = ",".join(f"{t:.2f}" for t in segment_times)

    cmd = [
        'ffmpeg', '-y',
        '-i', input_path,
        '-c', 'copy',
        '-map', '0',
        '-f', 'segment',
        '-segment_times', times_str,
        '-reset_timestamps', '1',
        '-segment_start_number', '1',
        f'{output_prefix}_%d.mp4'
    ]

    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        print(f"分割失败: {result.stderr.decode('utf-8')}")
    else:
        print(f"分割完成，输出文件前缀: {output_prefix}_")


def split_back(video_queue):
    print("split_back")
    needprocess = extract_videos_anyway(video_queue)
    print("split_back---:",needprocess)
    for task in needprocess:
        device_num =4
        try:
            # pritn(task["video_path"])
            split_video(task["video_path"], task["video"].split('.')[0], device_num)
        except Exception as e:
                    print(f"后台任务执行失败: {str(e)}")